import 'dart:convert';

import 'package:device_calendar/device_calendar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xiaozhou_ams_flutter/user/login.dart';
import 'package:xiaozhou_ams_flutter/tools.dart';
import 'package:http/http.dart' as http;
import '../api_client.dart';

class RegistrationPage extends StatefulWidget {
  const RegistrationPage({super.key});

  @override
  _RegistrationPageState createState() => _RegistrationPageState();
}

class _RegistrationPageState extends State<RegistrationPage> {

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();
  final TextEditingController _verificationCodeController = TextEditingController();
  String? _gender = '男';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注册'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,  // 对齐到起始位置
          children: [
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(
                labelText: '真实姓名',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.person),
              ),
            ),
            const SizedBox(height: 16.0),
            TextField(
              controller: _phoneController,
              decoration: const InputDecoration(
                labelText: '手机号',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.phone),
              ),
              keyboardType: TextInputType.phone,
            ),
            const SizedBox(height: 16.0),
            // 性别选择提示
            Padding(
              padding: const EdgeInsets.only(bottom: 8.0),
              child: Text(
                '请选择性别:',
                style: TextStyle(
                  fontSize: 18, // 增加字体大小
                  fontWeight: FontWeight.bold, // 字体加粗
                  color: Theme.of(context).primaryColor, // 使用主题颜色
                ),
              ),
            ),
            // 性别选择按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  child: RadioListTile<String>(
                    title: const Text('男'),
                    value: '男',
                    groupValue: _gender,
                    onChanged: (value) {
                      setState(() {
                        _gender = value;
                      });
                    },
                    activeColor: Colors.blue,
                    dense: true,
                  ),
                ),
                Expanded(
                  child: RadioListTile<String>(
                    title: const Text('女'),
                    value: '女',
                    groupValue: _gender,
                    onChanged: (value) {
                      setState(() {
                        _gender = value;
                      });
                    },
                    activeColor: Colors.pink,
                    dense: true,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16.0),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '密码',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.lock),
              ),
            ),
            const SizedBox(height: 16.0),
            TextField(
              controller: _confirmPasswordController,
              obscureText: true,
              decoration:const InputDecoration(
                labelText: '确认密码',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.lock),
              ),
            ),
            const SizedBox(height: 16.0),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _verificationCodeController,
                    decoration:const InputDecoration(
                      labelText: '验证码',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.security),
                    ),
                  ),
                ),
                const SizedBox(width: 16.0),
                ElevatedButton(
                  onPressed: () {
                    // TODO: 实现发送验证码的逻辑
                    sendVerificationCode(_phoneController.text);
                  },
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white, backgroundColor: Colors.blue, // 文字颜色
                  ),
                  child:const Text('发送验证码'),
                ),
              ],
            ),
            const SizedBox(height: 32.0),
            SizedBox(
              width: double.infinity, // 按钮宽度占满整个屏幕
              child: ElevatedButton(
                onPressed: () {
                  registerUser(
                      _nameController.text,
                      _phoneController.text,
                      _passwordController.text,
                      _confirmPasswordController.text,
                      _verificationCodeController.text,
                      _gender.toString()
                  );
                },
                style: ElevatedButton.styleFrom(
                  foregroundColor: Colors.white, backgroundColor: Colors.green, // 文字颜色
                ),
                child: const Text('注册'),
              ),
            ),
          ],
        ),
      ),
    );
  }
  //实现注册逻辑
  Future<void> registerUser(
      String username,
      String phone,
      String passWord,
      String confirmPassword,
      String verificationCode,
      String gender
      ) async {
    // try {
      // 判断用户填写的信息是否有空
      if (username.isEmpty || phone.isEmpty || passWord.isEmpty ||
          confirmPassword.isEmpty || verificationCode.isEmpty) {
        SnackbarHelper.showToast("请填写完整信息");
        return;
      }

      // 判断两次输入密码是否一样
      if (passWord != confirmPassword) {
        SnackbarHelper.showToast("两次密码不对，请重新填写！");
        return;
      }

      const String baseUrl = 'http://api.aiyuye.shop/';
      final prefs = await SharedPreferences.getInstance();
      final String? token = prefs.getString('userToken');
      final url = Uri.parse('$baseUrl/user/register?code=$verificationCode');

      // 构建数据包
      final formData = jsonEncode({
        'username': username,
        'passwordhash': passWord,
        'phone': phone,
        'sex':gender
      });

      final headers = {
        'Content-Type': 'application/json',
        'token':token.toString()
      };

      try{
        final response = await http.post(url, headers: headers, body: formData);
        if (response.statusCode == 200) {
          Map<String, dynamic> jsonMap = jsonDecode(response.body);
          print(jsonMap);
          // 请求成功，处理响应数据
          bool success = jsonMap['success'];
          String msg = jsonMap['msg'];

          if (success) {
            SnackbarHelper.showToast("注册成功！~");
            _navigateToLoginPage(); // 异步加载登录界面
            } else {
              SnackbarHelper.showToast(msg);
              }
          } else {
            SnackbarHelper.showToast("请求失败，服务器错误，请联系系统管理员！");
          }
    } catch (error) {
      SnackbarHelper.showToast("请求失败，服务器错误，请联系系统管理员！");
      if (kDebugMode) {
        print("Error: $error");
      }
    }
  }
  //实现发送验证码逻辑
  Future<void> sendVerificationCode(String phone)async {
    if (phone.isEmpty) {
      SnackbarHelper.showToast("请填写手机号码");
      return;
    }
    if(!isValidPhoneNumber(phone)){
      SnackbarHelper.showToast("请填写正确的手机号码");
      return;
    }
    final formData = {
      "phone" : phone
    };
    final response = await ApiClient.sendPostRequest('user/sentSmS', formData);
    try{
      if(response!=null){
        Map<String, dynamic> jsonMap = jsonDecode(response);
        String msg = jsonMap['msg'];
        bool success = jsonMap['success'];
        if(success){
          SnackbarHelper.showToast("验证码已经发送啦！~");
        }else{
          SnackbarHelper.showToast("出错啦！~ $msg");
        }
      }
    }catch(error){
      SnackbarHelper.showToast("请求失败，服务器错误，快快快联系系统管理员！");
      print("Error: $error");
    }
  }
  // 使用正则表达式匹配手机号格式
  bool isValidPhoneNumber(String phoneNumber) {
    RegExp regex = RegExp(r'^1[3456789]\d{9}$');
    return regex.hasMatch(phoneNumber);
  }

  _navigateToLoginPage(){
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => const LoginPage(),
      ),
    );
  }
}
